<template>
    <el-container>
        <!-- 左侧工作台 -->
        <el-aside width="250px!important"
            style="background-color: #f9f9f9; border-right: 1px solid #ebeef5; padding: 20px;">
            <div style="margin-bottom: 20px;">
                <el-button type="primary" plain icon="Plus" @click="createSession" style="width: 100%">
                    新建会话
                </el-button>
            </div>
            <el-scrollbar>
                <el-menu :default-active="activeSessionId" @select="handleSelectSession" style="border-right: none">
                    <el-menu-item v-for="session in sessions" :key="session.id" :index="session.id" class="menuItem">
                        <span @dblclick="renameSession(session)"
                            style="flex: 1; overflow: hidden; white-space: nowrap; text-overflow: ellipsis;text-align: start;padding-left: 5px;">
                            {{ session.name }}
                        </span>
                        <el-button type="text" size="small" @click.stop="deleteSession(session.id)"
                            style="margin-left: 5px">
                            删除
                        </el-button>
                    </el-menu-item>
                </el-menu>
            </el-scrollbar>
        </el-aside>

        <!-- 右侧对话区域 -->
        <el-container>
            <el-main style="display: flex; flex-direction: column; height: 100%; background: #ffffff;padding:0px;">

                <!-- 聊天内容滚动区域 -->
                <div ref="chatContainer" class="messagesBox">
                    <div v-for="(message, index) in currentSession.messages" :key="index" class="itemBox">
                        <div v-if="message.role === 'user'" style="justify-content: flex-end;">
                            <el-card shadow="always" class="userItemBox">
                                <div>{{ message.content }}</div>
                            </el-card>
                        </div>
                        <div v-else style="justify-content: flex-start;">
                            <div class="aiItemBox">
                                <div :class="{
                                    'thinkingLine': message.type === 'think',
                                    'answerLine': message.type === 'answer'
                                }">{{ message.content }}</div>
                            </div>

                        </div>
                    </div>

                </div>

                <!-- 输入框（不fixed了，靠flex布局到底部） -->
                <div class="inputBox">
                    <div class="inputMainBox">
                        <div class="textareaWrapper">
                            <textarea v-model="userInput" ref="textareaRef" class="chatTextarea" placeholder="询问任何问题"
                                @input="autoResize" @keydown="handleKeyDown"></textarea>

                            <div class="chatTool">
                                <button class="sendButton" @click="handleSend">
                                    <svg viewBox="0 0 24 24" width="20" height="20" fill="white">
                                        <path d="M2 21l21-9L2 3v7l15 2-15 2v7z"></path>
                                    </svg>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>

            </el-main>
        </el-container>
    </el-container>
</template>

<script>
export default {
    data() {
        return {
            STORAGE_KEY: 'chatgpt_sessions',
            sessions: this.loadSessions(),
            activeSessionId: '',
            userInput: '',
            isThinking: false,
            typingTimer: null,
        }
    },
    computed: {
        currentSession() {
            const session = this.sessions.find(s => s.id === this.activeSessionId);
            return session || { messages: [] };
        }
    },
    watch: {
        sessions: {
            handler() {
                this.saveSessions();
            },
            deep: true,
        }
    },
    mounted() {
        if (this.sessions.length > 0) {
            this.activeSessionId = this.sessions[0].id;
        }
        this.$nextTick(() => {
            this.scrollToBottom();
        });
    },
    methods: {
        createSession() {
            const id = `session-${Date.now()}`;
            this.sessions.push({
                id,
                name: '新的会话',
                messages: [],
            });
            this.activeSessionId = id;
            this.saveSessions();
        },
        handleSelectSession(id) {
            this.activeSessionId = id;
        },
        deleteSession(id) {
            this.$confirm('确定要删除该会话吗？', '提示', { type: 'warning' })
                .then(() => {
                    const index = this.sessions.findIndex(s => s.id === id);
                    if (index !== -1) {
                        this.sessions.splice(index, 1);
                        this.activeSessionId = this.sessions.length > 0 ? this.sessions[0].id : '';
                        this.saveSessions();
                    }
                })
                .catch(() => { });
        },
        renameSession(session) {
            this.$prompt('请输入新的会话名称', '重命名', {
                inputValue: session.name,
                confirmButtonText: '确定',
                cancelButtonText: '取消',
            })
                .then(({ value }) => {
                    session.name = value.trim() || '未命名会话';
                    this.saveSessions();
                })
                .catch(() => { });
        },
        async handleSend() {
            if (!this.userInput.trim()) {
                this.$message.warning('请输入内容');
                return;
            }

            const question = this.userInput.trim();
            this.userInput = '';
            this.$nextTick(() => this.autoResize());

            // 用户消息
            this.currentSession.messages.push({
                role: 'user',
                type: 'text',
                content: question
            });

            // AI 思考消息（灰色小字体）
            const thinkingMsg = {
                role: 'assistant',
                type: 'think',
                content: ''
            };
            this.currentSession.messages.push(thinkingMsg);

            // AI 正式回答消息
            const answerMsg = {
                role: 'assistant',
                type: 'answer',
                content: ''
            };
            this.currentSession.messages.push(answerMsg);

            this.$nextTick(() => this.scrollToBottom());

            try {
                const response = await fetch('http://localhost:5000/workspace/test/chat/stream', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        question,
                        user_id: '1',
                        online: false
                    })
                });

                const reader = response.body.getReader();
                const decoder = new TextDecoder('utf-8');
                let isThinkingPhase = true;

                while (true) {
                    const { value, done } = await reader.read();
                    if (done) break;

                    const chunk = decoder.decode(value, { stream: true });

                    chunk.split('\n\n').forEach(line => {
                        if (line.startsWith('data: ')) {
                            const payload = JSON.parse(line.replace('data: ', ''));
                            if (payload.delta) {
                                const text = payload.delta;

                                if (isThinkingPhase) {
                                    if (text.includes('</think>')) {
                                        const [thinkPart, realAnswer] = text.split('</think>');
                                        thinkingMsg.content += thinkPart.replace('<think>', '');
                                        isThinkingPhase = false;
                                        answerMsg.content += realAnswer;
                                    } else {
                                        thinkingMsg.content += text.replace('<think>', '');
                                    }
                                } else {
                                    answerMsg.content += text;
                                }

                                this.$nextTick(() => {
                                    this.scrollToBottom();
                                    this.saveSessions();
                                });
                            }
                        }
                    });
                }
            } catch (err) {
                console.error('请求失败：', err);
                this.$message.error('AI响应失败');
            }
        },
        simulateTyping(messageObj, fullAnswer) {
            let idx = 0;
            this.typingTimer = setInterval(() => {
                if (idx < fullAnswer.length) {
                    messageObj.content += fullAnswer[idx++];
                    this.currentSession.messages = [...this.currentSession.messages];
                    this.$nextTick(() => this.scrollToBottom());
                    this.saveSessions();
                } else {
                    clearInterval(this.typingTimer);
                }
            }, 50);
        },
        loadSessions() {
            try {
                const data = localStorage.getItem(this.STORAGE_KEY);
                if (data) {
                    return JSON.parse(data);
                }
            } catch (e) { }
            return [{ id: 'session-1', name: '新的会话', messages: [] }];
        },
        saveSessions() {
            localStorage.setItem(this.STORAGE_KEY, JSON.stringify(this.sessions));
        },
        scrollToBottom() {
            const container = this.$refs.chatContainer;
            if (container) {
                container.scrollTop = container.scrollHeight;
            }
        },
        autoResize() {
            const textarea = this.$refs.textareaRef;
            if (!textarea) return;

            textarea.style.height = 'auto';
            const scrollHeight = textarea.scrollHeight;
            const minHeight = 50;
            const maxHeight = 800;
            const finalHeight = Math.min(Math.max(scrollHeight, minHeight), maxHeight);

            textarea.style.height = finalHeight + 'px';

            if (scrollHeight > maxHeight) {
                textarea.style.overflowY = 'auto';
            } else {
                textarea.style.overflowY = 'hidden';
            }
        },
        handleKeyDown(event) {
            if (event.key === 'Enter') {
                if (event.shiftKey) {
                    return;
                } else {
                    event.preventDefault();
                    this.handleSend();
                }
            }
        }
    }
}
</script>


<style scoped>
body {
    margin: 0;
    font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
    background-color: #f0f2f5;
}

/* 左侧工作台悬停效果 */
.el-menu-item:hover {
    background-color: #ececec;
}

.menuItem {
    color: black;
    border-radius: 10px;
    height: 43px;
    line-height: 43px;
    padding: 0px !important;
    display: flex;
    justify-content: space-between;
    align-content: center;
    margin-bottom: 5px;
}

.el-menu-item.is-active {
    background-color: #e3e3e3;
}

/* 聊天内容区域 */
.messagesBox {
    flex: 1;
    overflow-y: auto;
    padding: 0px 50px;
}

/* 聊天消息气泡 */
.userItemBox {
    background-color: #e9e9e980;
    border-radius: 20px;
    display: inline-block;
    max-width: 70%;
}

.aiItemBox {
    margin: 20px 0px;
}

.itemBox {
    margin: 0px 50px;
}

.itemBox>div {
    display: flex;
    min-width: 500px;
}

/* 输入区域 */
.inputBox {
    padding: 0px 50px;
    display: flex;
    justify-content: center;
    align-items: center;
}

.inputMainBox {
    margin: 0px 50px;
    width: 100%;
    position: relative;
    display: flex;
    flex-direction: column;
}

/* textarea外壳 */
.textareaWrapper {
    position: relative;
    width: 100%;
    border-radius: 30px;
    border: 1px solid #ddd;
    box-shadow: 0px 0px 12px rgba(0, 0, 0, 0.12);
    padding: 10px;
    margin-bottom: 5px;
}

.chatTextarea {
    width: 100%;
    min-height: 30px;
    max-height: 200px;
    padding: 5px 0px 7px 5px;
    border: none;
    border-radius: 8px;
    resize: none;
    overflow-y: auto;
    font-size: 16px;
    outline: none;
    line-height: 1.5;
    letter-spacing: 0em;
    color: #1a1a1a;
    transition: height 0.2s ease;
    /* ✨ 加平滑过渡 */
}

.chatTextarea {
    transition: height 0.2s ease;
    /* ✨ 加平滑过渡动画 */
}

/* 发送按钮样式 */
.sendButton {
    background-color: black;
    border: none;
    border-radius: 50%;
    width: 30px;
    height: 30px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
}

.sendButton:hover {
    background-color: #333;
}

.chatTool {
    display: flex;
    justify-content: flex-end;
}

.home .el-aside {
    line-height: 0px;
}
.thinkingLine {
  font-size: 13px;
  color: #888;
  font-style: italic;
  white-space: pre-wrap;
}

.answerLine {
  font-size: 16px;
  color: #333;
  white-space: pre-wrap;
  line-height: 1.6;
  margin-top: 10px;
}

</style>